﻿using DotNetCore.CAP;
using Microsoft.AspNetCore.SignalR;
using Travel.API.Filters;
using Travel.CommonUtil.RedisUtil;
using Travel.Data;
using Travel.Data.Consts;
using Travel.Data.Inputs;

namespace Travel.API.Hubs
{
    /// <summary>
    /// 通讯中心
    /// </summary>
    //[TravelAuthorize]
    public class TravelHubs : Hub
    {
        private readonly ICapPublisher _publisher;

        public TravelHubs(ICapPublisher publisher)
        {
            _publisher = publisher;
        }

        /// <summary>
        /// 下订单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task OrderAdd(OrderAddInput input)
        {
            input.ConnectionId = Context.ConnectionId;
            input.LoginUserId = Convert.ToInt64(Context.User!.Claims.FirstOrDefault(p => p.Type.Equals("UserId"))!.Value);
            await _publisher.PublishAsync(EventBus.OrderAdd, input);
            await Clients.Client(Context.ConnectionId).SendAsync(SignalMethod.ReceiveMessage, Results<string>.DataResult("队列提交成功，请等待处理结果"));
        }

        public async Task ImportUser(string filePath)
        {
            ImportUserInput input = new ImportUserInput()
            {
                ConnectionId = Context.ConnectionId,
                FilePath = filePath,
                LoginUserId = Convert.ToInt64(Context.User!.Claims.FirstOrDefault(p => p.Type.Equals("UserId"))!.Value)
            };
            await _publisher.PublishAsync(EventBus.ImportUser, input);
            await Clients.Client(Context.ConnectionId).SendAsync(SignalMethod.ReceiveMessage, Results<string>.DataResult("队列提交成功，请等待处理结果"));
        }

        /// <summary>
        /// 当客户端连接成功时,保存当前用户对应的signalR连接ID
        /// </summary>
        /// <returns></returns>
        public override Task OnConnectedAsync()
        {
            var userId = Convert.ToInt64(Context.User.Claims.FirstOrDefault(p =>
            p.Type.Equals("UserId")).Value);
            CacheManager.Set(string.Format(Travel.Data.Consts.RedisKey.UserWebSocketConnectionId,
            userId), Context.ConnectionId);
            return Task.CompletedTask; ;
        }
        /// <summary>
        /// 当断开连接时，移除当前用户对应的SignalR连接ID
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(Exception? exception)
        {
            var userId = Convert.ToInt64(Context.User.Claims.FirstOrDefault(p =>
            p.Type.Equals("UserId")).Value);
            CacheManager.Remove(string.Format(Travel.Data.Consts.RedisKey.UserWebSocketConnectionId,
            userId));
            return Task.CompletedTask; ;
        }
    }
}
